"use strict";
var express = require('express');
var app = express();
var fs = require("fs");
var http = require('http');
var url = require('url');
var path = require('path');
var cp = require('child_process');
 
var bodyParser = require('body-parser');
var multer  = require('multer');
 
app.use('/public', express.static('public'));
app.use('/static', express.static('static'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}).array('image'));

app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization,\'Origin\',Accept,X-Requested-With');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.header('Access-Control-Allow-Credentials', true);
    res.header('X-Powered-By', ' 3.2.1');
    res.header('Content-Type', 'application/json;charset=utf-8');
    if (req.method === 'OPTIONS') {
        res.sendStatus(200);
    } else {
        next();
    }
});

app.get('/', function (req, res) {
  res.writeHead(200, { "content-type": "text/html" });
  var stream = fs.createReadStream(__dirname + "/" + "index.html" );
            //错误处理
            stream.on('error', function() {
                res.writeHead(500, { "content-type": contentType });
                res.end("<h1>500 Server Error</h1>");
            });
            //读取文件
            stream.pipe(res);
})

app.get('/index.html', function (req, res) {
  res.writeHead(200, { "content-type": "text/html" });
  var stream = fs.createReadStream(__dirname + "/" + "index.html" );
            //错误处理
            stream.on('error', function() {
                res.writeHead(500, { "content-type": contentType });
                res.end("<h1>500 Server Error</h1>");
            });
            //读取文件
            stream.pipe(res);
})
 
app.post('/file_upload', function (req, res) {
 
   console.log(req.files[0]);  // 上传的文件信息
 
   var des_file = __dirname + "/public/" + req.files[0].originalname;
   fs.readFile( req.files[0].path, function (err, data) {
        fs.writeFile(des_file, data, function (err) {
         if( err ){
                  res.end( JSON.stringify( {
                   message:'File uploaded successfully', 
                   "err": err
              } ) );
         }else{
          res.end( JSON.stringify( {
                   message:'File uploaded successfully', 
                   filename:req.files[0].originalname
              } ) );
        }
       });
   });
})

app.post('/file_clean', function (req, res) {
   var des_file = __dirname + "/public/";
   fs.readdir(des_file,function(err,data){
    if(err){
        res.end( JSON.stringify( {
                   message:'File clean error',
                   "err": err
              } ) );
    }
    console.log(data);  //data是数组类型，包含文件夹以及文件的名字(只有第一级目录内容)。拿到一个文件夹下面的所有目录  
    for (let f of data) {
      fs.unlink(des_file + "/" + f,function(error){
    if(error){
        console.log(error);
    }
    console.log('删除文件成功 ' + des_file + "/" + f);
})

    }
    res.end( JSON.stringify( {
                   message:'File clean successfully'
              } ) );
  });
})

app.post('/file_download', function (req, res) {
    //展示指定路径中的资源
    var filePath = path.resolve(__dirname + "/public");
    console.log(filePath);

    fs.stat(filePath, (err, stats) => {
        if (err) {
            res.writeHead(404, { "content-type": "text/html" });
            res.end("<h1>404 Not Found</h1>");
        }
        //如果路径是目录
        if (stats.isDirectory()) {
            var fileArray = [];
            //读取该路径下文件
            fs.readdir(filePath, (err, files) => {
                if (err) {
                    console.log("读取路径失败！");
                } else {
                    for (var file of files) {
                        fileArray.push(file)
                    }
                    res.end(JSON.stringify( fileArray));
                }
            });
        }
      });
})

app.get('/file_download/*', function (req, res) {
    //mime类型
    var mime = {
        "css": "text/css",
        "gif": "image/gif",
        "html": "text/html",
        "ico": "image/x-icon",
        "jpeg": "image/jpeg",
        "jpg": "image/jpeg",
        "js": "text/javascript",
        "json": "application/json",
        "pdf": "application/pdf",
        "png": "image/png",
        "svg": "image/svg+xml",
        "swf": "application/x-shockwave-flash",
        "tiff": "image/tiff",
        "txt": "text/plain",
        "wav": "audio/x-wav",
        "wma": "audio/x-ms-wma",
        "wmv": "video/x-ms-wmv",
        "xml": "text/xml"
    };
    
    //request里面切出标识符字符串
    var requestUrl = req.url;
    //url模块的parse方法 接受一个字符串，返回一个url对象,切出来路径
    var pathName = url.parse(requestUrl).pathname;

    //对路径解码，防止中文乱码
    var pathName = decodeURI(pathName);

    //解决301重定向问题，如果pathname没以/结尾，并且没有扩展名
    if (!pathName.endsWith('/') && path.extname(pathName) === '') {
        pathName += '/';
        var redirect = "http://" + req.headers.host + pathName;
        res.writeHead(301, {
            location: redirect
        });
        //res.end方法用来回应完成后关闭本次对话，也可以写入HTTP回应的具体内容。
        res.end();
    }

    //获取资源文件的绝对路径
    var filePath = path.resolve(__dirname + pathName);
    console.log(filePath);
    //获取对应文件的文档类型
    //我们通过path.extname来获取文件的后缀名。由于extname返回值包含”.”，所以通过slice方法来剔除掉”.”，
    //对于没有后缀名的文件，我们一律认为是unknown。
    var ext = path.extname(pathName);
    ext = ext ? ext.slice(1) : 'unknown';

    //未知的类型一律用"text/plain"类型
    var contentType = mime[ext] || "text/plain";

    fs.stat(filePath, (err, stats) => {
        if (err) {
            res.writeHead(404, { "content-type": "text/html" });
            res.end("<h1>404 Not Found</h1>");
        }
        //没出错 并且文件存在
        if (!err && stats.isFile()) {
            readFile(filePath, contentType);
        }
        //如果路径是目录
        if (!err && stats.isDirectory()) {
            var html = "<head><meta charset = 'utf-8'/></head><body><ul>";
            //读取该路径下文件
            fs.readdir(filePath, (err, files) => {
                if (err) {
                    console.log("读取路径失败！");
                } else {
                    //做成一个链接表，方便用户访问
                    var flag = false;
                    for (var file of files) {
                        //如果在目录下找到index.html，直接读取这个文件
                        if (file === "index.html") {
                            readFile(filePath + (filePath[filePath.length-1]=='/' ? '' : '/') + 'index.html', "text/html");
                            flag = true;
                            break;
                        };
                        html += `<li><a href='${file}'>${file}</a></li>`;
                    }
                    if(!flag) {
                        html += '</ul></body>';
                        res.writeHead(200, { "content-type": "text/html" });
                        res.end(html);
                        // res.end(JSON.stringify( {"aaa":"aaa"}));
                    }
                }
            });
        }

        //读取文件的函数
        function readFile(filePath, contentType){
            res.writeHead(200, { "content-type": contentType });
            //建立流对象，读文件
            var stream = fs.createReadStream(filePath);
            //错误处理
            stream.on('error', function() {
                res.writeHead(500, { "content-type": contentType });
                res.end("<h1>500 Server Error</h1>");
            });
            //读取文件
            stream.pipe(res);
        }
    });
})


var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("应用实例，访问地址为 http://%s:%s", host, port)
 
})